﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class SightController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Application.Admin.Sight.ISightPointAreaService sightAreaService;

        Application.Admin.Sight.ISightPointClassService sightClassService;

        Application.Admin.Sight.ISightPointService sightService;

        Application.Admin.Sight.ISightPointGoodsService sightGoodsService;

        Application.Admin.Sight.ISightPointImportLogService sightImportLogService;

        Application.Admin.Sight.ISightPointPicService sightPicService;

        Application.Admin.Sight.ISightPointCommService sightCommService;

        Application.Admin.Sight.ISightPointCommReplyService sightCommReplyService;

        Application.Admin.Sight.ISightPointUserSiginService sightSiginService;

        Application.Admin.Goods.IGoodsService goodsService;

        Application.Admin.Pic.IPicInfoService picService;

        public SightController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Application.Admin.Sight.ISightPointAreaService sightArea,
            Application.Admin.Sight.ISightPointClassService sightClass,
            Application.Admin.Sight.ISightPointService sight,
            Application.Admin.Sight.ISightPointGoodsService sightGoods,
            Application.Admin.Sight.ISightPointImportLogService sightImportLog,
            Application.Admin.Sight.ISightPointPicService sightPic,
            Application.Admin.Sight.ISightPointCommService sightComm,
            Application.Admin.Sight.ISightPointCommReplyService sightCommReply,
            Application.Admin.Sight.ISightPointUserSiginService sightSigin,
            Application.Admin.Goods.IGoodsService goods,
            Application.Admin.Pic.IPicInfoService pic)
            : base(work)
        {
            if (sightArea == null)
            {
                throw new ArgumentNullException("sightAreaService is null");
            }
            if (sightClass == null)
            {
                throw new ArgumentNullException("sightClassService is null");
            }
            if (sight == null)
            {
                throw new ArgumentNullException("sightService is null");
            }
            if (sightGoods == null)
            {
                throw new ArgumentNullException("sightGoodsService is null");
            }
            if (sightImportLog == null)
            {
                throw new ArgumentNullException("sightImportLogService is null");
            }
            if (sightPic == null)
            {
                throw new ArgumentNullException("sightPicService is null");
            }
            if (sightComm == null)
            {
                throw new ArgumentNullException("sightCommService is null");
            }
            if (sightCommReply == null)
            {
                throw new ArgumentNullException("sightCommReplyService is null");
            }
            if (sightSigin == null)
            {
                throw new ArgumentNullException("sightSiginService is null");
            }

            if (goods == null)
            {
                throw new ArgumentNullException("goodsService is null");
            }
            if (pic == null)
            {
                throw new ArgumentNullException("picService is null");
            }
            sightAreaService = sightArea;
            sightClassService = sightClass;
            sightService = sight;
            sightGoodsService = sightGoods;
            sightImportLogService = sightImportLog;
            sightPicService = sightPic;
            sightCommReplyService = sightCommReply;
            sightSiginService = sightSigin;
            sightCommService = sightComm;
            goodsService = goods;
            picService = pic;
        }

        #region sight

        public ActionResult Index()
        {
            //var data = this.GetSightPointTrueState();
            //return View(data.ToDto());
            var data = this.GetSightPointListTrueState();
            return View(data);
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey, int? areaId)
        {
            var data = this.GetSightPointListTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            if (areaId.HasValue)
            {
                if (areaId != 0)
                {
                    data = data.Where(e => e.AreaId == areaId);
                }
            }
            var dto = data;
            var model = new GridModel<Application.Admin.Dto.SightListDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult Add(Domain.Dto.SightPointDto dto)
        {
            dto.AddTime = System.DateTime.Now;
            dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            dto.SortNum = 0;
            dto.UserId = this.WorkContext.CurrentUser.Id;
            dto.UserName = this.WorkContext.CurrentUser.UserName;
            var entity = dto.ToEntity();
            sightService.Add(entity, this.WorkContext.CurrentUser);
            if (entity.Id > 0)
            {
                entity.InternalId = entity.Id;
                sightService.Modify(entity, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightPointListTrueState();
            var model = new GridModel<Application.Admin.Dto.SightListDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var delete = sightService.Get(id);
            if (delete != null)
            {
                sightService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightPointListTrueState();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = sightService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Edit(Domain.Dto.SightPointDto dto)
        {
            if (dto.Id > 0)
            {
                var entity = sightService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Name = dto.Name;
                    entity.Remark = dto.Remark;
                    entity.Lat = dto.Lat;
                    entity.Lon = dto.Lon;
                    if (!string.IsNullOrEmpty(dto.Address))
                    {
                        entity.Address = dto.Address;
                    }
                    entity.VouchNum = dto.VouchNum;
                    sightService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetSightPointListTrueState();
            var model = new GridModel<Application.Admin.Dto.SightListDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightPointTrueState().Where(e => e.Name.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetSightPointTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region detail

        public ActionResult Detail(int id)
        {
            var sight = sightService.Get(id);
            Application.Admin.Dto.SightDto data = null;
            if (sight != null)
            {
                data = this.GetSightDetailTrueState(sight);
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Detail(Domain.Dto.SightPointDto dto)
        {
            var res = false;
            var message = "";
            var entity = sightService.Get(dto.Id);
            if (entity != null)
            {
                entity.Name = dto.Name;
                entity.Remark = dto.Remark;
                entity.Lat = dto.Lat;
                entity.Lon = dto.Lon;
                entity.Address = dto.Address;
                entity.AreaId = dto.AreaId;
                entity.ClassId = dto.ClassId;
                entity.VouchNum = dto.VouchNum;
                try
                {
                    res = sightService.Modify(entity, this.WorkContext.CurrentUser);
                    message = res ? "" : "修改失败了T_T";
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            else
            {
                message = "没有找到，你要修改的景点信息";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region sight sigin

        public ViewResult SightSiginIndex(int id)
        {
            var data = this.GetSightSiginTrueState().Where(e => e.SightId == id);
            ViewBag.id = id;
            var sight = sightService.Get(id);
            if (sight != null)
            {
                ViewBag.sightname = sight.Name;
            }
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightSiginIndex(int targetId, string searchKey)
        {
            var data = this.GetSightSiginTrueState().Where(e => e.SightId == targetId);
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.UserName.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.SightPointUserSiginDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult SearchSightSigin(int targetId, string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightSiginTrueState().Where(e => e.SightId == targetId)
                    .Where(e => e.UserName.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.UserName).Distinct();

                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region sight comm

        #region comm version 2

        public ViewResult SightComment()
        {
            var data = this.GetSightCommTrueState().OrderByDescending(d => d.AddTime);
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightComment(string searchKey)
        {
            var data = this.GetSightCommTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Contents.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.SightPointCommDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteSightComment(int id)
        {
            var delete = sightCommService.Get(id);
            if (delete != null)
            {
                sightCommService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightCommTrueState();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult SearchSightComment(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightCommTrueState()
                    .Where(e => e.Contents.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.Contents).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region comm version 1

        public ViewResult SightCommIndex(int id)
        {
            var data = this.GetSightCommTrueState().Where(e => e.SightId == id);
            ViewBag.id = id;
            var sight = sightService.Get(id);
            if (sight != null)
            {
                ViewBag.sightname = sight.Name;
            }
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightCommIndex(int targetId, string searchKey)
        {
            var data = this.GetSightCommTrueState().Where(e => e.SightId == targetId);
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Contents.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.SightPointCommDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteSightComm(int targetId, int id)
        {
            var delete = sightCommService.Get(id);
            if (delete != null)
            {
                sightCommService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightCommTrueState().Where(e => e.SightId == targetId).ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeleteSightComm(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = sightCommService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult SearchSightComm(int targetId, string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightCommTrueState().Where(e => e.SightId == targetId)
                    .Where(e => e.Contents.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.Contents).Distinct();

                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region sight comm reply

        public ViewResult SightCommReplyIndex(int id)
        {
            var data = this.GetSightCommReplyTrueState().Where(e => e.CommId == id);
            ViewBag.id = id;
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightCommReplyIndex(int targetId, string searchKey)
        {
            var data = this.GetSightCommReplyTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Contents.Contains(searchKey));
            }
            var dto = data.Where(e => e.CommId == targetId).ToDto();
            var model = new GridModel<Domain.Dto.SightPointCommReplyDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult AddSightCommReply(Domain.Dto.SightPointCommReplyDto dto)
        {
            var res = false;
            var message = "";
            if (dto.CommId > 0 && !string.IsNullOrEmpty(dto.Contents))
            {
                var comm = sightCommService.Get(dto.CommId);
                if (comm != null)
                {
                    dto.AddTime = System.DateTime.Now;
                    dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                    dto.SortNum = 0;
                    dto.State = true;
                    dto.UserId = this.WorkContext.CurrentUser.Id;
                    dto.UserName = this.WorkContext.CurrentUser.UserName;
                    var entity = dto.ToEntity();
                    sightCommReplyService.Add(entity, this.WorkContext.CurrentUser);
                    comm.IsReply = true;
                    sightCommService.Modify(comm, this.WorkContext.CurrentUser);
                    if (entity.Id > 0)
                    {
                        res = true;
                    }
                    else
                    {
                        message = "回复失败了，亲，可以再来一次嘛！";
                    }
                }
                else
                {
                    message = "没有找到你要回复的评论";
                }
            }
            else
            {
                message = "请提交回复内容";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteSightCommReply(int targetId, int id)
        {
            var delete = sightCommReplyService.Get(id);
            if (delete != null)
            {
                sightCommReplyService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightCommReplyTrueState().Where(e => e.CommId == targetId).ToDto();
            if (data.Any())
            {
                var comm = sightCommService.Get(targetId);
                if (comm != null)
                {
                    comm.IsReply = false;
                    sightCommService.Modify(comm, this.WorkContext.CurrentUser);
                }
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeleteSightCommReply(int targetId, FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = sightCommReplyService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
                if (sightCommReplyService.GetList().Where(e => e.CommId == targetId).Any())
                {
                    var comm = sightCommService.Get(targetId);
                    if (comm != null)
                    {
                        comm.IsReply = false;
                        sightCommService.Modify(comm, this.WorkContext.CurrentUser);
                    }
                }
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult SearchShgitCommReply(int targetId, string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightCommReplyTrueState().Where(e => e.CommId == targetId)
                    .Where(e => e.Contents.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.Contents).Distinct();

                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }


        #endregion

        #endregion

        #region sight pic

        public ViewResult SightPicIndex(int id)
        {
            var sightPicId = sightPicService.GetList().Where(e => e.SightId == id)
                .Where(e => e.State == true).Select(e => e.PicInfoId);

            var data = picService.GetList().Where(e => sightPicId.Contains(e.Id))
                .Where(e => e.State == true).OrderByDescending(e => e.Id);

            var current = sightService.Get(id);
            ViewBag.current = current;
            return View(data.ToDto());
        }

        #endregion

        #region import export

        public ActionResult ExportSight()
        {
            return View();
        }

        public ActionResult ImportSight(HttpPostedFileBase importSightFile, string key)
        {
            var fileName = importSightFile.FileName;
            var suffix = System.IO.Path.GetExtension(fileName);
            var newFileName = System.DateTime.Now.ToFileTime() + suffix;
            var prePath = PreAdminConfigSettingService.ExcelSavePath.Substring(1);
            var webFullPath = prePath + newFileName;
            var savePath = System.IO.Path.Combine(Server.MapPath(PreAdminConfigSettingService.ExcelSavePath), newFileName);
            importSightFile.SaveAs(savePath);
            using (var excelService = new Infrastructure.Crosscutting.Comm.Service.ExcelService(savePath))
            {
                var excelData = excelService.ReadTable("Sheet1");
                //写入导入记录，
                #region add import log
                Domain.Entity.SightPointImportLog log = new Domain.Entity.SightPointImportLog();
                log.AddTime = System.DateTime.Now;
                log.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                log.Name = newFileName;
                log.PhyPrePath = prePath;
                log.SortNum = 0;
                log.SourceName = fileName;
                log.State = true;
                log.WebFullPath = webFullPath;
                log.WebPrePath = prePath;
                sightImportLogService.Add(log, this.WorkContext.CurrentUser);
                #endregion
                //添加excel中数据
                var allSightArea = sightAreaService.GetList().ToList();
                var allsightClass = sightClassService.GetList().ToList();
                if (excelData != null && excelData.Rows.Count > 0)
                {
                    var count = excelData.Rows.Count;
                    for (int i = 1; i < count; i++)
                    {
                        var internalIdStr = excelData.Rows[i][0].ToString();
                        var internalId = 0;
                        int.TryParse(internalIdStr, out internalId);

                        var name = excelData.Rows[i][1].ToString();
                        var strLon = excelData.Rows[i][2].ToString();
                        var strLat = excelData.Rows[i][3].ToString();
                        var lat = 0.0d;
                        var lon = 0.0d;
                        double.TryParse(strLat, out  lat);
                        double.TryParse(strLon, out  lon);

                        var vouchStr = excelData.Rows[i][4].ToString();
                        var vouchNum = 0;
                        int.TryParse(vouchStr, out vouchNum);

                        var address = excelData.Rows[i][5].ToString();
                        var area = excelData.Rows[i][6].ToString();
                        var cla = excelData.Rows[i][7].ToString();

                        Domain.Entity.SightPoint temp = null;
                        if (string.Compare(key, "keyName", false) == 0)
                        {
                            if (string.IsNullOrEmpty(name))
                            {
                                continue;
                            }
                            temp = sightService.GetList().Where(e => e.Name == name).FirstOrDefault();
                            if (temp != null)
                            {
                                temp.Lat = lat;
                                temp.Lon = lon;
                                temp.InternalId = internalId;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Modify(temp, this.WorkContext.CurrentUser);
                            }
                            else
                            {
                                temp = new Domain.Entity.SightPoint();
                                temp.Name = name;
                                temp.Remark = name;
                                temp.Lat = lat;
                                temp.Lon = lon;
                                temp.InternalId = internalId;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Add(temp, this.WorkContext.CurrentUser);
                            }
                        }
                        else if (string.Compare(key, "keyLatLon", false) == 0)
                        {
                            if (lat <= 0 || lon <= 0)
                            {
                                continue;
                            }
                            temp = sightService.GetList().Where(e => e.Lat == lat && e.Lon == lon).FirstOrDefault();
                            if (temp != null)
                            {
                                temp.Name = name;
                                temp.InternalId = internalId;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Modify(temp, this.WorkContext.CurrentUser);
                            }
                            else
                            {
                                temp = new Domain.Entity.SightPoint();
                                temp.Name = name;
                                temp.Remark = name;
                                temp.Lat = lat;
                                temp.Lon = lon;
                                temp.InternalId = internalId;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Add(temp, this.WorkContext.CurrentUser);
                            }
                        }
                        else if (string.Compare(key, "keyInternalId", false) == 0)
                        {
                            if (internalId <= 0)
                            {
                                continue;
                            }
                            temp = sightService.GetList().Where(e => e.InternalId == internalId).FirstOrDefault();
                            if (temp != null)
                            {
                                temp.Name = name;
                                temp.Remark = name;
                                temp.Lat = lat;
                                temp.Lon = lon;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Modify(temp, this.WorkContext.CurrentUser);
                            }
                            else
                            {
                                temp = new Domain.Entity.SightPoint();
                                temp.Name = name;
                                temp.Remark = name;
                                temp.Lat = lat;
                                temp.Lon = lon;
                                temp.InternalId = internalId;
                                InitSightImport(allSightArea, allsightClass, vouchNum, address, area, cla, temp);
                                sightService.Add(temp, this.WorkContext.CurrentUser);
                            }
                        }
                    }
                }
            }
            return RedirectToAction("Index");
        }

        #endregion

        #region sight area

        public ActionResult SightAreaIndex()
        {
            var data = this.GetSightAreaTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightAreaIndex(string searchKey)
        {
            var data = this.GetSightAreaTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.SightPointAreaDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult AddSightArea(Domain.Dto.SightPointAreaDto dto)
        {
            dto.AddTime = System.DateTime.Now;
            dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            dto.SortNum = 0;
            dto.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
            dto.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
            var entity = dto.ToEntity();
            sightAreaService.Add(entity, this.WorkContext.CurrentUser);
            var data = this.GetSightAreaTrueState();
            var model = new GridModel<Domain.Dto.SightPointAreaDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteSightArea(int id)
        {
            var delete = sightAreaService.Get(id);
            if (delete != null)
            {
                sightAreaService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightAreaTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeleteSightArea(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = sightAreaService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult EditSightArea(Domain.Dto.SightPointAreaDto dto)
        {
            if (dto.Id > 0)
            {
                var entity = sightAreaService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    entity.AreaType = string.IsNullOrEmpty(dto.AreaType) ? "" : dto.AreaType.Trim();
                    sightAreaService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetSightAreaTrueState();
            var model = new GridModel<Domain.Dto.SightPointAreaDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult SearchShgitArea(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightAreaTrueState().Where(e => e.Name.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetSightAreaTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region sight class

        public ActionResult SightClassIndex()
        {
            var data = this.GetSightClassTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxSightClassIndex(string searchKey)
        {
            var data = this.GetSightClassTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.SightPointClassDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult AddSightClass(Domain.Dto.SightPointClassDto dto)
        {
            dto.AddTime = System.DateTime.Now;
            dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            dto.SortNum = 0;
            dto.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
            dto.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
            var entity = dto.ToEntity();
            sightClassService.Add(entity, this.WorkContext.CurrentUser);
            var data = this.GetSightClassTrueState();
            var model = new GridModel<Domain.Dto.SightPointClassDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteSightClass(int id)
        {
            var delete = sightClassService.Get(id);
            if (delete != null)
            {
                sightClassService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetSightClassTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeleteSightClass(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = sightClassService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult EditSightClass(Domain.Dto.SightPointClassDto dto)
        {
            if (dto.Id > 0)
            {
                var entity = sightClassService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    sightClassService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetSightClassTrueState();
            var model = new GridModel<Domain.Dto.SightPointClassDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult SearchSightClass(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetSightClassTrueState().Where(e => e.Name.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetSightClassTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region util

        protected void InitSightImport(List<Domain.Entity.SightPointArea> allSightArea, List<Domain.Entity.SightPointClass> allSightClass,
          int vouch, string address, string area, string cla, Domain.Entity.SightPoint temp)
        {
            temp.Address = address;
            temp.AddTime = System.DateTime.Now;
            var tempArea = allSightArea.Where(e => e.Name.Contains(area)).FirstOrDefault();
            if (tempArea != null)
            {
                temp.AreaId = tempArea.Id;
            }
            var tempClass = allSightClass.Where(e => e.Name.Contains(cla)).FirstOrDefault();
            if (tempClass != null)
            {
                temp.ClassId = tempClass.Id;
            }
            temp.AudTime = null;
            temp.DeleteTime = null;
            //temp.Id
            temp.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            temp.IsAud = false;
            temp.IsDelete = false;
            temp.IsTop = false;
            temp.IsVouch = false;
            temp.SortNum = 0;
            temp.State = true;
            temp.TopTime = null;
            temp.UserId = this.WorkContext.CurrentUser.Id;
            temp.UserName = this.WorkContext.CurrentUser.UserName;
            temp.VouchTime = null;
            temp.VouchNum = vouch;
        }

        protected IQueryable<Domain.Entity.SightPointComm> GetSightCommTrueState()
        {
            var data = sightCommService.GetList().Where(e => e.State == true)
                .OrderBy(e => e.IsReply).ThenByDescending(e => e.Id);
            return data;
        }

        protected IQueryable<Domain.Entity.SightPointUserSigin> GetSightSiginTrueState()
        {
            var data = sightSiginService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id);
            return data;
        }

        protected IQueryable<Domain.Entity.SightPointCommReply> GetSightCommReplyTrueState()
        {
            var data = sightCommReplyService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id);
            return data;
        }

        /// <summary>
        /// Gets the state of the sight area true.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        protected IQueryable<Domain.Entity.SightPointArea> GetSightAreaTrueState()
        {
            var data = sightAreaService.GetList().Where(e => e.State == true).OrderByDescending(e => e.Id);
            return data;
        }

        /// <summary>
        /// Gets the state of the sight class true.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        protected IQueryable<Domain.Entity.SightPointClass> GetSightClassTrueState()
        {
            var data = sightClassService.GetList().Where(e => e.State == true).OrderByDescending(e => e.Id);
            return data;
        }

        /// <summary>
        /// Gets the state of the sight point true.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        protected IQueryable<Domain.Entity.SightPoint> GetSightPointTrueState()
        {
            var data = sightService.GetList().Where(e => e.State == true).OrderByDescending(e => e.Id);
            return data;
        }

        protected IQueryable<Application.Admin.Dto.SightListDto> GetSightPointListTrueState()
        {
            List<Application.Admin.Dto.SightListDto> data = new List<Application.Admin.Dto.SightListDto>();
            var all = sightService.GetList();
            if (this.WorkContext != null && this.WorkContext.CurrentUser != null && this.WorkContext.CurrentUser.Id > 3)
            {
                all = all.Where(e => e.UserId == this.WorkContext.CurrentUser.Id);
            }
            Application.Admin.Dto.SightListDto temp = null;
            foreach (var sight in all)
            {
                temp = new Application.Admin.Dto.SightListDto();
                temp.Address = sight.Address;
                temp.AddTime = sight.AddTime;
                temp.AreaId = sight.AreaId;
                temp.AudTime = sight.AudTime;
                temp.ClassId = sight.ClassId;
                temp.DeleteTime = sight.DeleteTime;
                temp.Id = sight.Id;
                temp.InternalId = sight.InternalId;
                temp.IpAddress = sight.IpAddress;
                temp.IsAud = sight.IsAud;
                temp.IsDelete = sight.IsDelete;
                temp.IsTop = sight.IsTop;
                temp.IsVouch = sight.IsVouch;
                temp.Lat = sight.Lat;
                temp.Lon = sight.Lon;
                temp.Name = sight.Name;
                temp.PicCount = (from sightPic in sightPicService.GetList()
                                 where sightPic.SightId == sight.Id
                                 select sightPic
                           ).Count() > 0 ? "有" : "无";
                temp.Remark = sight.Remark;
                temp.SortNum = sight.SortNum;
                temp.State = sight.State;
                temp.TopTime = sight.TopTime;
                temp.UserId = sight.UserId;
                temp.UserName = sight.UserName;
                temp.VouchNum = sight.VouchNum;
                temp.VouchTime = sight.VouchTime;
                data.Add(temp);
            }
            return data.OrderByDescending(e => e.Id).AsQueryable();
        }

        /// <summary>
        /// Gets the state of the sight detail true.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected Application.Admin.Dto.SightDto GetSightDetailTrueState(Domain.Entity.SightPoint entity)
        {
            #region sight base
            Application.Admin.Dto.SightDto data = new Application.Admin.Dto.SightDto();
            data.Address = entity.Address;
            data.AddTime = entity.AddTime;
            data.AreaId = entity.AreaId;
            data.AudTime = entity.AudTime;
            data.ClassId = entity.ClassId;
            data.DeleteTime = entity.DeleteTime;
            data.Id = entity.Id;
            data.IpAddress = entity.IpAddress;
            data.IsAud = entity.IsAud;
            data.IsDelete = entity.IsDelete;
            data.IsTop = entity.IsTop;
            data.IsVouch = entity.IsVouch;
            data.Lat = entity.Lat;
            data.Lon = entity.Lon;
            data.Name = entity.Name;
            data.Remark = entity.Remark;
            data.SortNum = entity.SortNum;
            data.State = entity.State;
            data.TopTime = entity.TopTime;
            data.UserId = entity.UserId;
            data.UserName = entity.UserName;
            data.VouchTime = entity.VouchTime;
            data.VouchNum = entity.VouchNum;

            #endregion

            data.SightArea = sightAreaService.Get(entity.AreaId).ToDto();
            data.SightClass = sightClassService.Get(entity.ClassId).ToDto();

            var goodsId = sightGoodsService.GetList().Where(e => e.SightId == entity.Id).Select(e => e.GoodsId);
            data.SightGoodsList = goodsService.GetList().Where(e => goodsId.Contains(e.Id)).ToDto().ToList();

            var picId = sightPicService.GetList().Where(e => e.SightId == entity.Id).Select(e => e.PicInfoId);
            data.SightPicList = picService.GetList().Where(e => picId.Contains(e.Id)).ToDto().ToList();

            return data;
        }

        #endregion
    }
}
